package cn.kevinproject.dingtalk_robot.client;

import cn.kevinproject.dingtalk_robot.robot.Robot;
import cn.kevinproject.dingtalk_robot.robot.RobotManger;
import com.dingtalk.api.DefaultDingTalkClient;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * @author kevin lau (双鹰)
 */
@Component
@RequiredArgsConstructor
public class ProducerFactory {

    private final RobotManger robotManger;

    private Map<String, Producer> producerCache;

    @PostConstruct
    public void init() {
        producerCache = new HashMap<>();
    }

    public Producer buildProducer(String robotName) {
        Robot robot = Optional.ofNullable(robotManger.getRobot(robotName)).orElseThrow(() -> new RuntimeException("can't find robot from name " + robotName));
        return producerCache.computeIfAbsent(robotName, name -> new Producer(new DefaultDingTalkClient(robot.getUrl())));
    }
}
